package com.motu.monstercity.server.game.web;


import com.motu.monstercity.module.common.redis.RedisKey;
import com.motu.monstercity.server.game.logic.GameUser;
import com.motu.monstercity.server.game.userdata.UserExtInfo;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.model.Model;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.ErrorWordManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.sun.mail.imap.protocol.UIDSet;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

public class EdituserdataHandler extends BaseWebHandler{
    private static final Logger logger = LoggerFactory.getLogger(EdituserdataHandler.class);

    public static final String tableName = "editshell";
    private static String packetPath = "com.motu.monstercity.server.game.userdata.";
    private static String modelPath = "com.motu.vertx.module.utility.model.";

    /*
     * 获取一条用户数据
     */
    public static void getone(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String table = json.getString("table");
        JsonArray listkey = json.getJsonArray("listkey");
        JsonArray params = new JsonArray();
        String sql1 = "SHOW FULL FIELDS FROM "+table;
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql1,params , handler1->{
            if(handler1.succeeded()){
                Future<JsonObject> fut= getOneData(table, listkey);
                fut.onComplete(handler->{
                    if(handler.succeeded()){
                        JsonArray list1 = handler1.result();
                        JsonObject entityObj = handler.result();//实体对象
                        if(list1 != null&&list1.size() > 0){
                            JsonArray list = new JsonArray();
                            String keys[] = {"Field","Type","Comment"};
                            for(int i=0;i<list1.size();i++){
                                JsonObject obj = new JsonObject();
                                String field = getHumpName(list1.getJsonObject(i).getString(keys[0]));// redis key:userName 数据库字段是:user_name
                                for(int j=0;j<keys.length;j++){
                                    obj.put(keys[j], list1.getJsonObject(i).getValue(keys[j]));
                                }
                                obj.put("Value", entityObj.getValue(field));
                                list.add(obj);
                            }
                            JsonObject result = new JsonObject();
                            result.put("total", list.size());
                            result.put("fields",list);
                            sendHttpResponse(response, result);

                        }else{
                            sendHttpResponseError(response, ErrorWord.MYSQL_QUERY_EMPTY);
                        }
                    }else{
                        sendHttpResponseError(response,handler.cause().getMessage());
                    }
                });

            }else{
                logger.error(handler1.cause().getMessage());
                sendHttpResponseError(response, ErrorWord.MYSQL_QUERY_FAILED);
            }
        });
    }

    /*
     * 用户数据列表查询
     */
    public static void getlist(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String table = json.getString("table");
        JsonArray listkey = json.getJsonArray("listkey");
        int projectid = json.getInteger("projectid");
        String sql1 = "SHOW FULL FIELDS FROM " + table;
        Future<JsonArray> fut1 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql1, new JsonArray());
        String sql2 = "select listkey from dbtable_info where projectid = ? and tablename = ?;";  //查询表的key字段
        JsonArray params2 = new JsonArray().add(projectid).add(table);
        Future<JsonArray> fut2 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getWebPool(), sql2, params2);
        Future<JsonArray> fut3 = getListData(table, listkey);
        CompositeFuture.all(fut1, fut2, fut3).onComplete(handler->{
            if (handler.succeeded()) {
                JsonArray fields = fut1.result();
                String key = fut2.result().getJsonObject(0).getString("listkey");
                JsonArray entityObjList = fut3.result();  //实体对象列表
                if (fields != null && fields.size() > 0){
                    JsonObject result = new JsonObject();
                    result.put("fields", fields);
                    result.put("key", key);
                    result.put("list", entityObjList);
                    System.out.println("###getlist entityObjList:" + result.getJsonArray("list"));
                    sendHttpResponse(response, result);
                } else {
                    sendHttpResponseError(response, ErrorWord.MYSQL_QUERY_EMPTY);
                }
            } else {
                sendHttpResponseError(response, handler.cause().getMessage());
            }
        });
    }

    public static void update(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String table = json.getString("table");
        JsonArray listkey = json.getJsonArray("listkey");
        JsonObject obj = json.getJsonObject("uobj");
        boolean saveShell = json.getBoolean("autosave");
        Future<JsonObject> fut = updateOneData(table, listkey, obj);
        fut.onComplete(handler->{
            if(handler.succeeded()){
                if (saveShell){

                    json.remove("autosave");
                    JsonArray shellList = new JsonArray();
                    shellList.add(json);
                    JsonObject obj2 = new JsonObject();
                    obj2.put("creator", adminName);
                    obj2.put("addtime", TimeUtils.getCurTime());
                    obj2.put("shell", shellList.toString());
                    obj2.put("name", json.getString("shellname"));
                    obj2.put("des", json.getString("shelldes"));
                    addToTable(obj2, MysqlClient.getServerPool(), tableName);//保存
                }else{//不保存脚本，则直接返回更新结果

                }
                JsonObject rets = handler.result();
                sendHttpResponse(response, new JsonObject().put("rets", rets));
            }else{
                sendHttpResponseError(response,handler.cause().getMessage());
            }
        });
    }

    /**
     * 删除用户数据,包括redis和Mysql
     * @param routingContext
     * @param json
     * @param adminName
     * @param client
     */
    public static void del(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String table = json.getString("table");
        JsonArray listkey = json.getJsonArray("listkey");

        Future<Integer> fut= delData(table, listkey);
        fut.onComplete(handler->{
            if (handler.succeeded()){
                Integer rets = handler.result();
                sendHttpResponse(response, new JsonObject().put("rets", rets));
            } else {
                sendHttpResponseError(response,handler.cause().getMessage());
            }
        });
    }

    /**
     * 删除对象,执行对象的delete方法
     * @param strClass
     * @return
     */
    public static Future<Integer> delData(String strClass, JsonArray listkey){
        Promise fut = Promise.promise();
        Class<?> threadClazz;
        try {
            threadClazz = Class.forName(modelPath + "EntityManager");
            Class[] ccc = new Class[] { Class.class,Object[].class };
//			Class[] ccc = id2 == null ? new Class[]{Class.class, long.class, String[].class} : new Class[]{Class.class, long.class, long.class, String[].class};
            Method method = threadClazz.getMethod("getEntity", ccc);
            Class<?> entityClazz = Class.forName(packetPath + Tool.captureName(getHumpName(strClass)));
            Object[] keyList = new Object[listkey.size()];
            for (int i = 0; i < listkey.size(); i++) {
                keyList[i] = listkey.getValue(i);
            }
            Object[] ooo = new Object[] { entityClazz,keyList };
//			Object[] ooo = id2 == null ? new Object[]{entityClazz, id1.longValue(), new String[0]} : new Object[]{entityClazz, id1.longValue(), id2.longValue(), new String[0]};
            Model model = (Model) method.invoke(null, ooo);
            if (model != null) {
                model.delete();// 删除
                fut.complete(0);
            } else {
                fut.complete(1);
            }

        } catch (Exception e) {
            logger.error(Tool.getException(e));
            fut.fail(e.getMessage());
        }
        return fut.future();
    }

    public static Future<JsonObject> getOneData(String strClass,JsonArray listkey){
        Promise fut = Promise.promise();
        Class<?> threadClazz;
        try {
            threadClazz = Class.forName(modelPath + "EntityManager");
            Class[] ccc = new Class[] { Class.class,Object[].class };
            Method method = threadClazz.getMethod("getEntityObject",  ccc);
            Class<?> entityClazz = Class.forName(packetPath + Tool.captureName(getHumpName(strClass)));
            Object[] keyList = new Object[listkey.size()];
            for (int i = 0; i < listkey.size(); i++) {
                keyList[i] = listkey.getValue(i);
            }
            Object[] ooo = new Object[] { entityClazz,keyList };
            JsonObject obj = (JsonObject) method.invoke(null,ooo);
            if (obj != null) {
                fut.complete(obj);
            } else {
                logger.error("!!!!! getOneData error model is null  strClass:"+strClass+" listkey:"+listkey.toString() );
                fut.fail(ErrorWordManager.get(ErrorWord.REDIS_QUERY_EMPTY));
            }
        } catch (Exception e) {
            logger.error(Tool.getException(e));
            fut.fail(e.getMessage());
        }
        return fut.future();
    }


    public static Future<JsonArray> getListData(String strClass, JsonArray listkey){
        Promise fut = Promise.promise();
        Class<?> threadClazz;
        try {
            threadClazz = Class.forName(modelPath + "EntityManager");
            Class[] ccc = listkey.size() == 0 ? new Class[] { Class.class} :new Class[] { Class.class, String.class};
            Method method = threadClazz.getMethod("getEntityArray",  ccc);
            Class<?> entityClazz = Class.forName(packetPath + Tool.captureName(getHumpName(strClass)));
            String key = listkey.size() == 0 ? "" : String.valueOf(listkey.getValue(0));
            Object[] ooo =  new Object[] { entityClazz,key};
            JsonArray arr = (JsonArray) method.invoke(null, ooo);
            System.out.println("###getListData result:" + arr);
            if(arr != null){
                fut.complete(arr);
            }else{
                logger.error("!!!!! getListData error model is null  strClass:" + strClass + " listkey:" + listkey.toString());
                fut.fail(ErrorWordManager.get(ErrorWord.REDIS_QUERY_EMPTY));
            }
        } catch (Exception e) {
            logger.error(Tool.getException(e));
            fut.fail(e.getMessage());
        }
        return fut.future();
    }

    public static Future<JsonObject> updateOneData(String strClass,JsonArray listkey,JsonObject obj){
        Promise fut = Promise.promise();
        JsonArray params = new JsonArray();
        String sql = "SHOW FULL FIELDS FROM "+strClass+";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params, res->{
            if(res.succeeded()){
                JsonArray array = res.result();
                Class<?> threadClazz;
                try {
                    threadClazz = Class.forName(modelPath + "EntityManager");
                    Class[] ccc = new Class[] { Class.class,Object[].class };
                    Method method = threadClazz.getMethod("getEntity",  ccc);
                    Class<?> entityClazz = Class.forName(packetPath + Tool.captureName(getHumpName(strClass)));
                    Object[] keyList = new Object[listkey.size()];
                    for (int i = 0; i < listkey.size(); i++) {
                        keyList[i] = listkey.getValue(i);
                    }
                    Object[] ooo = new Object[] { entityClazz,keyList };
                    Model model = (Model)method.invoke(null,ooo);
                    if(model != null){
                        Iterator<Entry<String, Object>> it = obj.iterator();
                        boolean isUpdate = false;
                        JsonObject updateRet = new JsonObject();
                        while(it.hasNext()){
                            Entry<String, Object> entry = it.next();
                            String field = entry.getKey();
                            if(isPriKey(array, field)){
                                continue;//主键不能修改
                            }
                            Object value = entry.getValue();
                            String strMethod = "put"+Tool.captureName(getHumpName(field));// 字段vip_score 调用方法:putVipScore
                            String fieldValueType = getFieldValueType(array, field);
                            //System.out.println("updateOneData strClass:"+strClass+" id:"+id1+ " id2:"+(id2==null?"null":id2)+" field:"+field+ " value:"+value);
                            if(fieldValueType != null){
                                Class<?> valueClass = getValueClass(fieldValueType);
                                Method method2 = model.getClass().getSuperclass().getDeclaredMethod(strMethod,valueClass);
                                //System.out.println("updateOneData strClass:"+strClass+" valueClass:"+valueClass.getName());
                                if(valueClass.getName().equalsIgnoreCase("byte")){
                                    //System.out.println("byte 1!!!1");
                                    method2.invoke(model, ((Integer)value).byteValue());
                                }else if(valueClass.getName().equalsIgnoreCase("short")){
                                    method2.invoke(model, ((Integer)value).shortValue());
                                }else{
                                    method2.invoke(model, value);
                                }
                                isUpdate = true;
                                updateRet.put(field, value);
                            }else{
                                logger.error("!!!! updateOneData error fieldValueType is null strClass:"+strClass+" listkey:"+listkey.toString()+ " field:"+field+ " value:"+value);
                            }
                        }
                        if(isUpdate){
                            Method method3 = model.getClass().getSuperclass().getDeclaredMethod("update");
                            method3.invoke(model);
                        }
                        fut.complete(updateRet);
                    }else{
                        logger.error("!!!!! updateOneData error model is null  strClass:"+strClass+" listkey:"+listkey.toString());
                        fut.fail(ErrorWordManager.get(ErrorWord.REDIS_QUERY_EMPTY));
                    }
                } catch (Exception e) {
                    logger.error(Tool.getException(e));
                    fut.fail(e.getMessage());
                }
            }else{
                fut.fail(ErrorWordManager.get(ErrorWord.MYSQL_QUERY_FAILED));
            }
        });
        return fut.future();
    }

    private static String getFieldValueType(JsonArray array,String field){
        for(int i=0;i<array.size();i++){
            JsonObject obj = array.getJsonObject(i);
            if(obj.getString("Field").equalsIgnoreCase(field)){
                return obj.getString("Type");
            }
        }
        return null;
    }

    /**
     * 根据表名称,返回相应的类名称 如user_info,返回userInfo
     * @param tabelName
     * @return
     */
    private static String getHumpName(String tabelName) {
        String className = "";
        String str[] = tabelName.split("_");
        for (int i=0; i<str.length; i++) {
            if (i == 0) {
                className = str[i];
            } else {
                className += Tool.captureName(str[i]);// 首字母大写,再拼接
            }
        }
        return className;
    }

    private static boolean isPriKey(JsonArray array,String field){
        for(int i=0;i<array.size();i++){
            JsonObject obj = array.getJsonObject(i);
            if(obj.getString("Field").equalsIgnoreCase(field)){
                return obj.getString("Key").equalsIgnoreCase("PRI");
            }
        }
        return false;
    }

    private static Class<?> getValueClass(String type){
        if(type.startsWith("bigint")){
            return long.class;
        }else if(type.startsWith("int")){
            return int.class;
        }else if(type.startsWith("tinyint")){
            return byte.class;
        }else if(type.startsWith("smallint")){
            return short.class;
        }else if(type.startsWith("varchar") || type.startsWith("text")){
            return String.class;
        }else if(type.startsWith("float")){
            return float.class;
        }else if(type.startsWith("double")){
            return double.class;
        }
        return Object.class;
    }


    public static void shell_list(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        getTableList(routingContext, MysqlClient.getServerPool(), tableName);
    }

    public static void shell_add(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        addToTable(routingContext, MysqlClient.getServerPool(), tableName,null);
    }

    public static void shell_update(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        updateToTable(routingContext, MysqlClient.getServerPool(), tableName,null);
    }

    public static void shell_getone(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        getFromTable(routingContext, MysqlClient.getServerPool(), tableName);

    }
    public static void shell_delete(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        deleteFromTable(routingContext, MysqlClient.getServerPool(), tableName);
    }

    public static void shell_search(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        if(!json.containsKey("key")&&!json.containsKey("creator")){
            shell_list(routingContext, json, adminName, client);
            return;
        }

        boolean hasKey = json.containsKey("key");
        boolean hasCreator = json.containsKey("creator");
        String str1 = " and (name like ? or des like ?)";
        String str11 = " and creator like ?";
        String key = hasKey?json.getString("key"):"";
        String sql1 = "select count(1) FROM "+tableName+" where 1=1 ";

        JsonArray params1 = new JsonArray();

        if(hasKey){
            sql1 += str1;
            params1.add("%"+key+"%");
            params1.add("%"+key+"%");
        }
        if(hasCreator){
            sql1 += str11;
            params1.add("%"+json.getString("creator")+"%");

        }

        String sql = "select * FROM "+tableName+" where  id > 0 ";
        String str2 = " order by id desc  limit ?,?; ";
        JsonArray params = new JsonArray();

        if(hasKey){
            sql += str1;
            params.add("%"+key+"%");
            params.add("%"+key+"%");
        }
        if(hasCreator){
            sql += str11;
            params.add("%"+json.getString("creator")+"%");

        }

        int pageNo = json.getInteger("pageNo");
        int pageSize = json.getInteger("pageSize");
        int start = pageNo*pageSize;
        params.add(start);
        params.add(pageSize);
        sql += str2;
        searchFromTable(routingContext, MysqlClient.getServerPool(), tableName, sql1, params1, sql, params);
    }

    public static void shell_merge(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        JsonArray idList = json.getJsonArray("ids");
        Future<JsonArray> fut = mergeShells(idList);
        HttpServerResponse response = routingContext.response();
        fut.onComplete(handler->{
            if(handler.succeeded()){
                JsonArray rets = handler.result();
                JsonObject obj = new JsonObject();
                obj.put("creator", adminName);
                obj.put("addtime", TimeUtils.getCurTime());
                obj.put("shell", rets.toString());
                addToTable(routingContext, MysqlClient.getServerPool(), tableName,obj);//合并后插入
            }else{
                sendHttpResponseError(response,handler.cause().getMessage());
            }
        });
    }

    private static  Future<JsonArray> mergeShells(JsonArray idList){
        Promise fut = Promise.promise();
        JsonArray params = new JsonArray();
        String idStr = idList.toString();
        idStr = idStr.substring(1, idStr.length()-1);
        String sql = "select shell from editshell where id in("+idStr+");";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql, params, res->{
            if(res.succeeded()){
                JsonArray mergeList = new  JsonArray();
                JsonArray array = res.result();
                for(int i=0;i<array.size();i++){
                    JsonObject obj = array.getJsonObject(i);
                    JsonArray shellList = new JsonArray(obj.getString("shell"));
                    for(int k=0;k<shellList.size();k++){
                        mergeList.add(shellList.getJsonObject(k));
                    }
                }
                fut.complete(mergeList);
            }else{
                fut.fail(ErrorWordManager.get(ErrorWord.MYSQL_QUERY_FAILED));
            }
        });
        return fut.future();
    }

//	public static void shell_execute(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
//		long id = json.getLong("id");
//		String sql = "select shell from editshell where id = ?;";
//		JsonArray params = new JsonArray();
//		params.add(id);
//		HttpServerResponse response = routingContext.response();
//		MysqlTool.queryJsonArrayFromDb(MainVerticle.instance.jdbcClientServer, sql, params,  Sync.fiberHandler(res->{
//			if(res.succeeded()){
//				JsonArray array = res.result();
//				if(array.size() > 0){
//					JsonArray retList = new  JsonArray();
//					JsonObject obj = array.getJsonObject(0);
//					JsonArray shellList = new JsonArray(obj.getString("shell"));
//					List<Future> futList = new ArrayList<Future>();
//					for(int k=0;k<shellList.size();k++){
//						futList.add(Future.future());
//					}
//					for(int k=0;k<shellList.size();k++){
//						JsonObject obj2 = shellList.getJsonObject(k);
//						String table = obj2.getString("table");
//						Long id1 = obj2.getLong("id1");
//						Long id2 = obj2.getLong("id2");
//
//						JsonObject uobj = obj2.getJsonObject("uobj");
//						Future<JsonObject> fut = updateOneData(table, id1, id2, uobj);
//						int index = k;
//						fut.onComplete(handler->{
//							JsonObject robj = new JsonObject();
//							robj.put("shell", obj2);
//							if(handler.succeeded()){
//								robj.put("result", "ok");
//							}else{
//								robj.put("result", handler.cause().getMessage());
//							}
//							retList.add(robj);
//							futList.get(index).complete();
//						});
//					}
//					CompositeFuture.all(futList).onComplete(res2->{
//						sendHttpResponse(response, new JsonObject().put("rets", retList));
//					});
//
//				}else{
//					sendHttpResponseError(response, ErrorWord.MYSQL_QUERY_EMPTY);
//				}
//			}else{
//				sendHttpResponseError(response, ErrorWord.MYSQL_QUERY_FAILED);
//			}
//		}));
//	}

    /**
     * 游戏服redis 查询
     * @param routingContext
     * @param json
     * @param adminName
     * @param client
     */
    public static void redisSearch(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String key = json.getString("key");
        int type = json.getInteger("type");
        if (type == 0) {// 获取对象
            RedisTools.getHashJsonObject(key, handler->{
                if (handler.succeeded()) {
                    sendHttpResponse(response, new JsonObject().put("data", handler.result()));
                } else {
                    sendHttpResponseError(response, handler.cause().getMessage());
                }
            });
        } else if (type == 1) {// 获取列表
            RedisTools.getJsonArray(key, handler->{
                if (handler.succeeded()) {
                    sendHttpResponse(response, new JsonObject().put("data", handler.result()));
                } else {
                    sendHttpResponseError(response, handler.cause().getMessage());
                }
            });
        } else if (type == 2) {// 获取字符串
            RedisTools.get(key, handler->{
                if (handler.succeeded()) {
                    sendHttpResponse(response, new JsonObject().put("data", handler.result()));
                } else {
                    sendHttpResponseError(response, handler.cause().getMessage());
                }
            });
        } else if (type == 3) {// 获取榜单
            int from = json.containsKey("from") ? json.getInteger("from") : 0;
            int to = json.containsKey("to") ? json.getInteger("to") : 200;
            boolean isScore = json.getBoolean("isscore");// 是否显示分数
            RedisTools.getRankListByIndex(key, from, to - 1, isScore, handler->{
                if (handler.succeeded()) {
                    sendHttpResponse(response, new JsonObject().put("data", handler.result()));
                } else {
                    sendHttpResponseError(response, handler.cause().getMessage());
                }
            });
        } else {
            sendHttpResponse(response, new JsonObject().put("data", ""));
        }
    }

    /**
     * 设置 redis 初始化key
     * @param routingContext
     * @param json
     * @param adminName
     * @param client
     */
    public static void setRedisInitKey(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        HttpServerResponse response = routingContext.response();
        String table = json.getString("table");
        String redisKey = json.getString("redisKey");
        int initType = json.getInteger("initType");
        String key = table + "." + redisKey;
        if (initType == 0) {
            // 设置对象的初始化key
            String initKey = EntityManager.getEntityInitKey(key);
            RedisTools.set(initKey, "1");// 把initkey 值设置为1
            String isInit = Future.await(RedisTools.get(initKey));
            JsonObject result = new JsonObject();
            result.put(initKey,isInit);
            sendHttpResponse(response, new JsonObject().put("data", result));
        } else if (initType == 1) {
            // 设置列表的初始化key
            String listkey = "list." + key;
            JsonArray result = new JsonArray();
            JsonArray list = Future.await(RedisTools.getJsonArray(listkey));
            for (int i = 0; i < list.size(); i++) {
                String iKey = table + "." + list.getString(i);
                String initKey = EntityManager.getEntityInitKey(iKey);
                RedisTools.set(initKey, "1");// 把initkey 值设置为1
                String isInit = Future.await(RedisTools.get(initKey));
                JsonObject keyInfo = new JsonObject();
                keyInfo.put(initKey,isInit);
                result.add(keyInfo);
            }
            sendHttpResponse(response, new JsonObject().put("data", result));
        } else if (initType == 2) {
            //整表修复
            //RepairCodeManager.resetRedisInitKeyByList(table,redisKey);
            sendHttpResponse(response, new JsonObject());
        }else {
            sendHttpResponse(response, new JsonObject().put("data", ""));
        }
    }


    /***
     * 两个账号互换绑
     * @param routingContext
     */
    public static void exchangeAccountid(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        long userIdA = json.getLong("userid");
        long userIdB = json.getLong("rebbindUserid");

        UserExtInfo userextinfoA = GameUser.getUserExtInfo(userIdA);
        if (userextinfoA == null) {
            sendHttpResponseError(routingContext.response(), "userextinfoA 不存在 userid = " + userIdA);
            return;
        }
        UserExtInfo userextinfoB = GameUser.getUserExtInfo(userIdB);
        if (userextinfoB == null) {
            sendHttpResponseError(routingContext.response(), "userextinfoB 不存在 userid = " + userIdB);
            return;
        }
        String accountIdA = userextinfoA.getAccountId();
        int accountTypeA = userextinfoA.getAccountType();
        String accountIdB = userextinfoB.getAccountId();
        int accountTypeB = userextinfoB.getAccountType();

        userextinfoA.putAccountId(accountIdB);
        userextinfoA.putAccountType(accountTypeB);
        userextinfoA.updateQueueNow();

        userextinfoB.putAccountId(accountIdA);
        userextinfoB.putAccountType(accountTypeA);
        userextinfoB.updateQueueNow();

        sendHttpResponse(routingContext.response(), new JsonObject());
        sendLog(routingContext, new JsonObject());
    }

    /***
     * 重绑账号
     * @param routingContext
     */
    public static void rebind(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
        long userId = json.getLong("userid");
        String accountId = json.getString("account");
        int accountType = json.getInteger("accountType");
        UserExtInfo userextinfo = GameUser.getUserExtInfo(userId);
        if (userextinfo == null) {
            sendHttpResponseError(routingContext.response(), "userextinfo 不存在 userid = " + userId);
            return;
        }
        userextinfo.putAccountId(accountId);
        userextinfo.putAccountType(accountType);
        userextinfo.updateQueueNow();
        sendHttpResponse(routingContext.response(), new JsonObject());
        sendLog(routingContext, new JsonObject());
    }

    /*
     * 查看玩家网关信息
     */
    public static void getUserGateObj(RoutingContext routingContext, JsonObject json, String adminName, WebClient client){
        HttpServerResponse response = routingContext.response();
        JsonObject result = new JsonObject();
        long userid = json.getLong("userid");
        String redisKey = RedisKey.getUserLoginDeviceKey(userid);
        String str = Future.await(RedisTools.get(redisKey));
        JsonObject gobj = new JsonObject();
        if (str != null && !str.isEmpty()) {
            gobj = new JsonObject(str);
        }
        boolean isConnect = GameUser.isConnect(userid);
        result.put("isConnect", isConnect);
        result.put("gobj", gobj);
        sendHttpResponse(response, new JsonObject().put("result", result));
    }

}
